#!/bin/bash
#created by leo

echo "=== begin icon add version"
pwd
CURRENT_PATH=`cd $(dirname $0); pwd -P`
cd $CURRENT_PATH
pwd

convert_path=`which convert`
gs_path=`which gs`

if [[ ! -f ${convert_path} || -z ${convert_path} ]]; then
  convert_valid=true;
else
  convert_valid=false;
fi

if [[ ! -f ${gs_path} || -z ${gs_path} ]]; then
  gs_valid=true;
else
  gs_valid=false;
fi

if [[ "$convert_valid" = true || "$gs_valid" = true ]]; then
  echo "WARNING: skip icon version, you need to install ImageMagick and ghostscript (fonts) first, you can use brew to simplify process:"

  if [[ "$convert_valid" = true ]]; then
    echo "brew install imagemagick"
  fi
  if [[ "$gs_valid" = true ]]; then
    echo "brew install ghostscript"
  fi
exit 0;
fi

version=`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${CONFIGURATION_BUILD_DIR}/${INFOPLIST_PATH}"`
build_num=`/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${CONFIGURATION_BUILD_DIR}/${INFOPLIST_PATH}"`

echo "${version}"
echo "${build_num}"

old_version_path=./icon_version.txt
if [ ! -d $old_version_path ]; then
	touch $old_version_path
fi
old_version=`cat $old_version_path`
echo $old_version
if [[ $old_version == $version ]]; then
	echo "已添加过，不再重复添加"
	exit 0;
fi

date_now="$(date +"%Y.%m.%d")"
icon_path=${SRCROOT}/$TARGETNAME/Assets.xcassets/AppIcon.appiconset
copy_icon_path=./icon_copy
if [ ! -d $copy_icon_path ]; then
  cp -r $icon_path $copy_icon_path
fi

function read_dir() {
  for file in `ls $1`
    do
      if [ -d $1"/"$file ]
      then
        read_dir $1"/"$file
      else
        if [ "${file##*.}"x = "png"x ];then
          icon_width=`identify -format "%[fx:w]" $1"/"$file`
          echo $icon_width
          mark_width=$icon_width
          mark_hight=`expr $mark_width / 3`
          convert -background '#0005' -fill white -gravity center -size "${mark_width}x${mark_hight}" caption:"${version}\n${date_now}" $copy_icon_path"/"$file +swap -gravity south -composite $1"/"$file
          echo "处理图片${file}"
        fi
    fi
  done
}
read_dir $icon_path
echo $version > icon_version.txt

echo "=== end icon add version"
